//
//  XLDoctor
//
//  Created by longma on 2018/7/31.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "HealthHelper.h"
#import "WPVersionUpdateView.h"

#import "SelectTestItemAlertView.h"
#import "DetectionPeriodtAlertView.h"
#import "DetectionItemViewController.h"
#import "MJMultipleDetectionResultVC.h"
#import "MJGoutDetectionResultVC.h"
#import "MJHemoglobinDetectionResultVC.h"
#import "MJBloodSugarDetectionResultVC.h"
#import "MJTotalDetectionResultVC.h"
#import "CaptchaView.h"
#import "MemberInfoVC.h"
#import "CountryCodeModel.h"

@interface HealthHelper ()

@end

@implementation HealthHelper

/**
 单例
 */
+ (instancetype)shared{
    static HealthHelper *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HealthHelper alloc] init];
    });
    return instance;
}

+ (void)setThemeMode:(NSString *)theme {
    
    NSNumber *themeStyle = @(MJThemeStyleDefault);
    if([theme isEqualToString:@"默认"]){
        themeStyle = @(MJThemeStyleDefault);
    }
    if([theme isEqualToString:@"科技"]){
        themeStyle = @(MJThemeStyleTechnology);
    }
    if([theme isEqualToString:@"中医"]){
        themeStyle = @(MJThemeStyleTCM);
    }
    HealthHelper.shared.themeStyle = themeStyle;
    [MJUIUserDeFault setObject:themeStyle.description forKey:MJ_AppTheme];
}

+ (NSString *)getThemeModeName:(MJThemeStyle)mThemeStyle {
    if(mThemeStyle == MJThemeStyleDefault){
        return @"默认";
    }
    if(mThemeStyle == MJThemeStyleTechnology){
        return @"科技";
    }
    if(mThemeStyle == MJThemeStyleTCM){
        return @"中医";
    }
    return @"默认";
}

+ (void)checkUpdateBlock:(void(^)(NSDictionary *data))updateBlock{
    
    [MJHttpNetWorking requestWithParams:@{@"appName":@"Isaw⁺",@"deviceType":@"iOS"} requestUri:appBasis_getAppUpgrade requestType:RequestTypeGet showLoading:false success:^(MJBaseModel *model) {
        
        NSInteger versionCode = [[NSString mj_appVersionNum] integerValue];
        NSInteger newVersionCode = [model.data[@"newVersion"] integerValue];
        //获取本地版本号
        NSString *versionCodeString = [MJUIUserDeFault objectForKey:MJ_AppVersionCode];
        if(versionCodeString){
            versionCode = [versionCodeString integerValue];
        }
        if (versionCode < newVersionCode) {
            ///// <
            updateBlock(model.data);
        }else{
            updateBlock(nil);
        }
    } failure:^(NSError *error) {
        
    }];
}

+ (void)appUpgradeWithToast:(BOOL)isShowToast{
    
    if(!HealthHelper.shared.isGetAppUpgrade){
        
        //设置版本号
        [MJUIUserDeFault setObject:@"135" forKey:MJ_AppVersionCode];
        
        [MJHttpNetWorking requestWithParams:@{@"appName":@"Isaw⁺",@"deviceType":@"iOS"} requestUri:appBasis_getAppUpgrade requestType:RequestTypeGet showLoading:isShowToast success:^(MJBaseModel *model) {
            
            HealthHelper.shared.isGetAppUpgrade = true;
            NSLog(@"MJLog==========model=============%@",model.data);
            NSInteger versionCode = [[NSString mj_appVersionNum] integerValue];
            NSInteger newVersionCode = [model.data[@"newVersion"] integerValue];
            //获取本地版本号
            NSString *versionCodeString = [MJUIUserDeFault objectForKey:MJ_AppVersionCode];
            if(versionCodeString){
                versionCode = [versionCodeString integerValue];
            }

            //是否低于最小版本
            BOOL forceUpdate = [model.data[@"forceUpdate"] boolValue];
            NSInteger minVersionCode = [model.data[@"minVersion"] integerValue];
            if(versionCode < minVersionCode){
                forceUpdate = true;
            }
            //
            if (versionCode < newVersionCode) {
                [WPVersionUpdateView showUpdateViewWithMessage:model.data[@"updateDescription"]?:@"" version:model.data[@"newVersion"] forceUpdate:forceUpdate apkUrl:model.data[@"apkUrl"]];
            }else{
                if(isShowToast){
                    
                    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
                    configure.confirmButtonColor = UIColor.mj_appColor;
                    configure.confirmTitle = MJUILocalizedString(@"OK_qd");
                    configure.hiddenCancelButton = true;
                    configure.messageAlignmentCenter = true;
                    NSString *messageString = MJUILocalizedString(@"The version 1.0.0 is the latest");
                    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"No updates available") message:messageString configure:configure confirmBlock:^{
                        
                    } cancelBlock:^{

                    }];
                }
            }
        } failure:^(NSError *error) {
            
        }];
    }
    
}

+ (NSArray *)getHealthAreaCodesDataSource {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HealthAreaCodes" ofType:@"plist"];
    NSArray *dataSource = [[NSArray alloc] initWithContentsOfFile:filePath];
    return dataSource;
}

+ (NSMutableArray *)getAreaCodesDataSource {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"AreaCodes" ofType:@"plist"];
    NSDictionary *dataSource = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    
    /*
     按NSDictionary的key来对其进行排序： NSDictionary排序
     先将dict的allkeys赋给一个数组，然后通过sortedArrayUsingComparator:方法对数组排序，然后遍历数组取字典对应key的值
     */
    NSArray *keys = [dataSource allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

    NSMutableArray *dataArray = [NSMutableArray array];
    for (NSString *categoryId in sortedArray) {
        [dataArray addObject:@{@"section":categoryId,@"array":[dataSource objectForKey:categoryId]}];
    }
    return dataArray;
}

+ (NSArray *)getAreaCodesKeyArray {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"AreaCodes" ofType:@"plist"];
    NSDictionary *dataSource = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    
    /*
     按NSDictionary的key来对其进行排序： NSDictionary排序
     先将dict的allkeys赋给一个数组，然后通过sortedArrayUsingComparator:方法对数组排序，然后遍历数组取字典对应key的值
     */
    NSArray *keys = [dataSource allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    return sortedArray;
}

+ (NSMutableArray *)getAreaCodesJsonDataSource{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"国际号段" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSArray *dataSourceArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSMutableArray *dataArray = [NSMutableArray arrayWithArray:dataSourceArray];
    return dataArray;
}

#pragma mark -
+ (NSMutableArray *)getAreaCodesJsonArray {
    
    NSMutableArray *dataArray = [self getAreaCodesJsonDataSource];
    NSMutableArray *array = [NSMutableArray array];

    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
        
        //数组排序
        for (int i=0; i<dataArray.count-1; i++){
            
            for (int j=i+1; j<dataArray.count; j++) {
                
                NSString *name = dataArray[i][@"俄语"];
                NSString *nameNext = dataArray[j][@"俄语"];
                NSInteger nameFirstLetter = [name.mj_letterRuToInt intValue];
                NSInteger nameNextFirstLetter = [nameNext.mj_letterRuToInt intValue];
                
                if (nameFirstLetter > nameNextFirstLetter) {
                    
                    NSDictionary *TempDic=[[dataArray objectAtIndex:i]copy];
                    
                    dataArray[i] = [[dataArray objectAtIndex:j] copy];
                    
                    dataArray[j]= TempDic;
                }
                
            }
        }
        
        //
        for (int i = 0; i < dataArray.count; i++) {

            BOOL isHaveGroup = false;
            NSDictionary *data = dataArray[i];
            
            NSString *name = data[@"俄语"];
            
            unichar letter = [name characterAtIndex:0];
            NSString *firstLetter = [NSString stringWithCharacters:&letter length:1];

            //循环查找是否有当前月份的分组，若没有则创建分组
            for (int j = 0; j < array.count; j++) {
                
                NSMutableDictionary *dic = array[j];
                NSString *section = dic[@"section"];

                NSMutableArray *itemArray = dic[@"array"];
                if([section isEqualToString:firstLetter]){
                    
                    [itemArray addObject:data];
                    isHaveGroup = true;
                }
            }
            if(!isHaveGroup){
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSMutableArray *itemArray = [NSMutableArray arrayWithObject:data];
                [dic setObject:itemArray forKey:@"array"];
                [dic setObject:firstLetter forKey:@"section"];
                [array addObject:dic];
            }
               
        }
        
    }else{
        
        if(LanguageHelper.shared.mLanguageStyle != MJLanguageStyleEN){
            //数组排序
            for (int i=0; i<dataArray.count-1; i++){
                
                for (int j=i+1; j<dataArray.count; j++) {
                    
                    NSString *name = dataArray[i][@"中文名"];
                    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
                        name = dataArray[i][@"印尼语"];
                    }
                    NSString *nameNext = dataArray[j][@"中文名"];
                    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
                        nameNext = dataArray[j][@"印尼语"];
                    }
                    
                    NSInteger nameFirstLetter = [name.mj_firstLetter.mj_letterToInt intValue];
                    NSInteger nameNextFirstLetter = [nameNext.mj_firstLetter.mj_letterToInt intValue];
                    
                    if (nameFirstLetter > nameNextFirstLetter) {
                        
                        NSDictionary *TempDic=[[dataArray objectAtIndex:i]copy];
                        
                        dataArray[i] = [[dataArray objectAtIndex:j] copy];
                        
                        dataArray[j]= TempDic;
                    }
                    
                }
            }
        }
        
        //
        for (int i = 0; i < dataArray.count; i++) {

            BOOL isHaveGroup = false;
            NSDictionary *data = dataArray[i];
            
            NSString *name = data[@"英文名"];
            if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
                name = data[@"英文名"];
            }else if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
                name = data[@"印尼语"];
            }else{
                name = data[@"中文名"];
            }
            NSString *firstLetter = name.mj_firstLetter;
            //循环查找是否有当前月份的分组，若没有则创建分组
            for (int j = 0; j < array.count; j++) {
                
                NSMutableDictionary *dic = array[j];
                NSString *section = dic[@"section"];

                NSMutableArray *itemArray = dic[@"array"];
                if([section isEqualToString:firstLetter]){
                    
                    [itemArray addObject:data];
                    isHaveGroup = true;
                }
            }
            if(!isHaveGroup){
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSMutableArray *itemArray = [NSMutableArray arrayWithObject:data];
                [dic setObject:itemArray forKey:@"array"];
                [dic setObject:firstLetter forKey:@"section"];
                [array addObject:dic];
            }
               
        }
    }
    
    
    return array;
}

+ (NSMutableArray *)getAreaCodesJsonKeyArray:(NSMutableArray *)array {
    
    NSMutableArray *keyArray = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
        NSString *key = obj[@"section"];
        [keyArray addObject:key];
    }];
    return keyArray;
}

+ (NSDictionary *)getCountryAreaCode {
  
    NSLocale *locale = [NSLocale currentLocale];
    // 获取国家代码
    NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
    // 获取国家名
    NSString *displayName = [locale displayNameForKey:NSLocaleCountryCode value:countryCode];
    NSLog(@"Country Code: %@", countryCode);
    NSLog(@"Country Name: %@", displayName);
    
    NSArray *array = [self getAreaCodesJsonDataSource];
    NSDictionary *countryAreaCode = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ISO == %@", countryCode]];
    return countryAreaCode;
}

+ (NSString *)getCountryNameWithCountryISO:(NSString *)countryISO {
    
    NSArray *array = [self getAreaCodesJsonDataSource];
    NSDictionary *countryArea;
    for (NSDictionary *dic in array) {
        NSString *code = dic[@"ISO"];
        if([code isEqualToString:countryISO]){
            countryArea = dic;
            break;
        }
    }
    NSString *countryAreaName = @"";
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
        countryAreaName = countryArea[@"英文名"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
        countryAreaName = countryArea[@"中文名"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
        countryAreaName = countryArea[@"港澳繁体"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
        countryAreaName = countryArea[@"台湾繁体"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
        countryAreaName = countryArea[@"俄语"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
        countryAreaName = countryArea[@"印尼语"];
    }
    return countryAreaName;
}

//+ (NSString *)getCountryNameWithCountryCode:(NSString *)countryCode {
//    
//    NSArray *array = [self getAreaCodesJsonDataSource];
//    NSDictionary *countryArea;
//    for (NSDictionary *dic in array) {
//        NSString *code = dic[@"区号"];
//        if([code isEqualToString:countryCode]){
//            countryArea = dic;
//            break;
//        }
//    }
//    NSString *countryAreaName = @"";
//    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
//        countryAreaName = countryArea[@"英文名"];
//    }
//    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
//        countryAreaName = countryArea[@"中文名"];
//    }
//    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
//        countryAreaName = countryArea[@"港澳繁体"];
//    }
//    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
//        countryAreaName = countryArea[@"台湾繁体"];
//    }
//    return countryAreaName;
//}

+ (NSString *)getCountryNameWithCountryName:(NSString *)countryName {
    
    NSArray *dataSourceArray = [self getAreaCodesJsonDataSource];
    NSMutableArray *array = [NSMutableArray array];
    [dataSourceArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
        CountryCodeModel *model = [[CountryCodeModel alloc]init];
        model.nameEN = obj[@"英文名"];
        model.nameZhHansCN = obj[@"中文名"];
        model.nameZhHantCN = obj[@"港澳繁体"];
        model.nameZhHantTW = obj[@"台湾繁体"];
        model.nameRU = obj[@"俄语"];
        model.nameID = obj[@"印尼语"];

        model.ID = obj[@"id"];
        model.code = obj[@"区号"];
        model.ISO = obj[@"ISO"];
        [array addObject:model];
    }];
    
    CountryCodeModel *nameEN = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameEN == %@", countryName]];
    CountryCodeModel *nameZhHansCN = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameZhHansCN == %@", countryName]];
    CountryCodeModel *nameZhHantCN = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameZhHantCN == %@", countryName]];
    CountryCodeModel *nameZhHantTW = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameZhHantTW == %@", countryName]];
    CountryCodeModel *nameRU = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameRU == %@", countryName]];
    CountryCodeModel *nameID = [array mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nameID == %@", countryName]];
    
    CountryCodeModel *model;
    if(nameEN){
        model = nameEN;
    }else if(nameZhHansCN){
        model = nameZhHansCN;
    }else if(nameZhHantCN){
        model = nameZhHantCN;
    }else if(nameZhHantTW){
        model = nameZhHantTW;
    }else if(nameRU){
        model = nameRU;
    }else if(nameID){
        model = nameID;
    }
    
    NSString *countryAreaName = @"";
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
        countryAreaName = model.nameEN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
        countryAreaName = model.nameZhHansCN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
        countryAreaName = model.nameZhHantCN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
        countryAreaName = model.nameZhHantTW;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
        countryAreaName = model.nameRU;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
        countryAreaName = model.nameID;
    }
    
    return countryAreaName;
}

+ (NSDictionary *)getCountryWithCountryCode:(NSString *)countryCode {
    
    NSArray *array = [self getAreaCodesJsonDataSource];
    NSDictionary *countryArea;
    for (NSDictionary *dic in array) {
        NSString *code = dic[@"区号"];
        if([code isEqualToString:countryCode]){
            countryArea = dic;
            break;
        }
    }
    return countryArea;
}

+ (NSString *)getCountryAreaName {
  
    NSString *countryAreaName = @"";
    NSDictionary *countryArea = [HealthHelper getCountryAreaCode];
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
        countryAreaName = countryArea[@"英文名"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
        countryAreaName = countryArea[@"中文名"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
        countryAreaName = countryArea[@"港澳繁体"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
        countryAreaName = countryArea[@"台湾繁体"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
        countryAreaName = countryArea[@"俄语"];
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
        countryAreaName = countryArea[@"印尼语"];
    }
    return countryAreaName;
}

+ (UIButton *)initItemButton:(UIView *)superview {
    UIButton *button = [[UIButton alloc]init];
    button.backgroundColor = UIColor.clearColor;
    [superview addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superview);
    }];
    return button;
}

+(NSMutableArray *)itemMonthGroupArray:(NSMutableArray *)dataSourceArray aClass:(Class)aClass{
    
    
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < dataSourceArray.count; i++) {

        BOOL isHaveGroup = false;
        
        RecordDataBaseModel *data;
        if(aClass == MJGoutDetectionModel.class){
            data = dataSourceArray[i];
        }
        
        NSString *dateTime = [HealthHelper timeZoneWithDateTime:data.createDateTime dateFormat:MJUIDateFormat9];
//        NSLog(@"dateTime11111=======================%@",dateTime);
        //循环查找是否有当前月份的分组，若没有则创建分组
        for (int j = 0; j < array.count; j++) {
            
            NSMutableDictionary *dic = array[j];
            NSString *month = dic[@"month"];
            NSMutableArray *itemArray = dic[@"array"];
            if([month isEqualToString:dateTime]){
                [itemArray addObject:data];
                isHaveGroup = true;
            }
        }
        
        if(!isHaveGroup){
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSMutableArray *itemArray = [NSMutableArray arrayWithObject:data];
            [dic setObject:itemArray forKey:@"array"];
            [dic setObject:dateTime forKey:@"month"];
            [array addObject:dic];
        }
    }
    return array;
}

+ (void)jumpDetectionViewControllerWith:(PatientModel *)patientModel viewController:(UIViewController *)viewController {
    
    SelectTestItemAlertView *selectTestItemAlertView = [[SelectTestItemAlertView alloc] init];
    selectTestItemAlertView.confirmBlock = ^(DetectionItemType detectionItemType) {
        
        DetectionPeriodtAlertView *detectionPeriodtAlertView = [[DetectionPeriodtAlertView alloc] init];
        detectionPeriodtAlertView.confirmBlock = ^(NSString *period) {
            [HealthHelper jumpDetectionViewController:patientModel detectionItemType:detectionItemType period:period viewController:viewController];
        };
        detectionPeriodtAlertView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        viewController.modalPresentationStyle = UIModalPresentationCurrentContext;
        [viewController.navigationController presentViewController:detectionPeriodtAlertView animated:NO completion:nil];
    };
    selectTestItemAlertView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    viewController.modalPresentationStyle = UIModalPresentationCurrentContext;
    [viewController.navigationController presentViewController:selectTestItemAlertView animated:NO completion:nil];
}

+ (void)jumpDetectionViewController:(PatientModel *)patientModel detectionItemType:(DetectionItemType)detectionItemType period:(NSString *)period viewController:(UIViewController *)viewController {
    
    DetectionItemViewController *vc = [[DetectionItemViewController alloc]init];
    vc.detectionItemType = detectionItemType;
    vc.period = period;
    vc.patientId = patientModel.patientId;
    [viewController.navigationController pushViewController:vc animated:true];
    
//    if(detectionItemType == DetectionItemTypeGout){
//    }
//    if(detectionItemType == DetectionItemTypeGlu){
//        
//    }
//    if(detectionItemType == DetectionItemTypeTC){
//        
//    }
//    if(detectionItemType == DetectionItemTypeHB){
//        
//    }
//    if(detectionItemType == DetectionItemTypeMultiple){
//        
//    }
}

+ (UIColor *)getTCColorWithGradeStr:(NSString *)grade {
    NSArray *colorArr = @[@"#1AD5A3",@"#F59B18",@"#EB8888",@"#BA0202"];
    UIColor *indexColor;
    if([grade isEqualToString:@"Low"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[0]];
    }
    if([grade isEqualToString:@"MR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[1]];
    }
    if([grade isEqualToString:@"HR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[2]];
    }
    if([grade isEqualToString:@"VHR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[3]];
    }
    return indexColor;
}

+ (NSInteger)getTCGradeInteger:(NSString *)grade {
    NSInteger index = 0;
    if([grade isEqualToString:@"Low"]){
        index = 0;
    }
    if([grade isEqualToString:@"MR"]){
        index = 1;
    }
    if([grade isEqualToString:@"HR"]){
        index = 2;
    }
    if([grade isEqualToString:@"VHR"]){
        index = 3;
    }
    return index;
}

+ (UIColor *)getGluColorWithGradeStr:(NSString *)grade {
    NSArray *colorArr = @[@"#BEDB73",@"#1AD5A3",@"#F59B18",@"#EB8888",@"#BA0202"];
    UIColor *indexColor;
    if([grade isEqualToString:@"Hypo"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[0]];
    }
    if([grade isEqualToString:@"Normal"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[1]];
    }
    if([grade isEqualToString:@"Prediabetes"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[2]];
    }
    if([grade isEqualToString:@"Diabetes"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[3]];
    }
    if([grade isEqualToString:@"DKA"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[3]];
    }
    return indexColor;
}

+ (NSInteger)getGluGradeInteger:(NSString *)grade {
    NSInteger index = 0;
    if([grade isEqualToString:@"Hypo"]){
        index = 0;
    }
    if([grade isEqualToString:@"Normal"]){
        index = 1;
    }
    if([grade isEqualToString:@"Prediabetes"]){
        index = 2;
    }
    if([grade isEqualToString:@"Diabetes"]){
        index = 3;
    }
    if([grade isEqualToString:@"DKA"]){
        index = 4;
    }
    return index;
}

+ (UIColor *)getHBColorWithGradeStr:(NSString *)grade {
    NSArray *colorArr = @[@"#1AD5A3",@"#BEDB73",@"#F59B18",@"#EB8888",@"#BA0202"];
    UIColor *indexColor;
    if([grade isEqualToString:@"Min"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[0]];
    }
    if([grade isEqualToString:@"Low"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[1]];
    }
    if([grade isEqualToString:@"MR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[2]];
    }
    if([grade isEqualToString:@"HR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[3]];
    }
    if([grade isEqualToString:@"VHR"]){
        indexColor = [UIColor mj_colorWithHexString:colorArr[4]];
    }
    return indexColor;
}

+ (NSInteger)getHBGradeInteger:(NSString *)grade {
    NSInteger index = 0;
    if([grade isEqualToString:@"Min"]){
        index = 0;
    }
    if([grade isEqualToString:@"Low"]){
        index = 1;
    }
    if([grade isEqualToString:@"MR"]){
        index = 2;
    }
    if([grade isEqualToString:@"HR"]){
        index = 3;
    }
    if([grade isEqualToString:@"VHR"]){
        index = 4;
    }
    return index;
}

+ (NSString *)detectionTitle:(DetectionItemType)detectionItemType {
    if(detectionItemType == DetectionItemTypeMultiple){
        return MJUILocalizedString(@"Multiple Testing");
    }
    if(detectionItemType == DetectionItemTypeGout){
        return MJUILocalizedString(@"Uric Acid Testing");
    }
    if(detectionItemType == DetectionItemTypeHB){
        return MJUILocalizedString(@"Hemoglobin Testing");
    }
    if(detectionItemType == DetectionItemTypeGlu){
        return MJUILocalizedString(@"Blood Glucose Testing");
    }
    if(detectionItemType == DetectionItemTypeTC){
        return MJUILocalizedString(@"Total Cholesterol Testing");
    }
    return @"";
}

+ (void)jumpDetectionResultController:(DetectionItemType)detectionItemType model:(id)model viewController:(UIViewController *)viewController completion:(void (^)(void))completion{
    
    if(detectionItemType == DetectionItemTypeMultiple){
        MJMultipleDetectionResultVC *vc = [[MJMultipleDetectionResultVC alloc]initWithModel:(MJMultipleModel *)model];
        vc.isFromDetection = true;
        [viewController.navigationController mj_pushViewController:vc animated:true completion:^{
            completion();
        }];
        [WCBDHelper.shared mj_insertMultipleObjectWithModel:(MJMultipleModel *)model];
    }
    if(detectionItemType == DetectionItemTypeGout){
        MJGoutDetectionResultVC *vc = [[MJGoutDetectionResultVC alloc]initWithModel:(MJGoutDetectionModel *)model];
        vc.isFromDetection = true;
        [viewController.navigationController mj_pushViewController:vc animated:true completion:^{
            completion();
        }];
        [WCBDHelper.shared mj_insertGoutObjectWithModel:(MJGoutDetectionModel *)model];
    }
    if(detectionItemType == DetectionItemTypeHB){
        MJHemoglobinDetectionResultVC *vc = [[MJHemoglobinDetectionResultVC alloc]initWithModel:(MJHemoglobinModel *)model];
        vc.isFromDetection = true;
        [viewController.navigationController mj_pushViewController:vc animated:true completion:^{
            completion();
        }];
        [WCBDHelper.shared mj_insertHemoglobinObjectWithModel:(MJHemoglobinModel *)model];

    }
    if(detectionItemType == DetectionItemTypeGlu){
        MJBloodSugarDetectionResultVC *vc = [[MJBloodSugarDetectionResultVC alloc]initWithModel:(MJBloodSugarModel *)model];
        vc.isFromDetection = true;
        [viewController.navigationController mj_pushViewController:vc animated:true completion:^{
            completion();
        }];
        [WCBDHelper.shared mj_insertBloodSugarObjectWithModel:(MJBloodSugarModel *)model];

    }
    if(detectionItemType == DetectionItemTypeTC){
        MJTotalDetectionResultVC *vc = [[MJTotalDetectionResultVC alloc]initWithModel:(MJTotalCholesterolModel *)model];
        vc.isFromDetection = true;
        [viewController.navigationController mj_pushViewController:vc animated:true completion:^{
            completion();
        }];
        [WCBDHelper.shared mj_insertTotalCholesterolObjectWithModel:(MJTotalCholesterolModel *)model];

    }
}

+ (PatientModel *)getpatientModel:(NSString *)patientId {
    PatientModel *patientModel = [HealthHelper.shared.homePatientList mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"patientId == %@", patientId]];
    return patientModel;
}

+ (void)showCaptchaViewWithPhoneNumber:(NSString *)phoneNumber countryAreaCode:(NSDictionary *)countryAreaCode completion:(void (^)(MJBaseModel *model))completion {
    
    MJWeakSelf
    [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
        NSLog(@"result=======================%@",result);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"countryCode": countryAreaCode[@"区号"],
            @"phoneNumber": phoneNumber,
            @"region": countryAreaCode[@"ISO"],
            @"code": result,
        }];
        [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendSms requestType:RequestTypePost showLoading:true success:^(MJBaseModel *model) {
            
            completion(model);
            
        } failure:^(NSError *error) {
            
        }];
    }];
}

+ (void)showCaptchaViewWithEmail:(NSString *)email completion:(void (^)(MJBaseModel *model))completion {
    
    [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
        NSLog(@"result=======================%@",result);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"email": email,
            @"code": result,
        }];
        [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendEmail requestType:RequestTypePost showLoading:true success:^(MJBaseModel *model) {
            
            completion(model);
            
        } failure:^(NSError *error) {
            
        }];
    }];
}

+ (NSString *)timeZoneWithDateTime:(NSString *)createDateTime dateFormat:(NSString *)dateFormat{
    
    //北京时间
    NSDateFormatter *beijingFormatter = [[NSDateFormatter alloc] init];
    beijingFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [beijingFormatter setDateFormat:MJUIDateFormat];
    NSTimeZone *beijingZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [beijingFormatter setTimeZone:beijingZone];
    NSDate *beijingDate = [beijingFormatter dateFromString:createDateTime];

    // 目标时区
    NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
    localFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [localFormatter setDateFormat:dateFormat];
    NSTimeZone *localZone = [NSTimeZone systemTimeZone];//当前手机设置的是纽约时区
    [localFormatter setTimeZone:localZone];

    NSString* localTimeString = [localFormatter stringFromDate:beijingDate];//换成本地(纽约)时间:2022-05-18 04:19:34

//    NSLog(@"源时区时间：%@", createDateTime); // 输出：源时区时间：2021-08-02 12:00:00
//    NSLog(@"目标时区时间：%@", localTimeString); // 输出：目标时区时间：2021-08-02 00:00:00

    return localTimeString;
}

- (MJMultipleModel *)createMJMultipleModel {
    MJHemoglobinModel *recordDataBaseModel = [MJHemoglobinModel yy_modelWithDictionary:@{
        @"detectionId":@"1806267858894692390",
        @"period":@"Fasting",
        @"createDateTime":@"2024-07-05 17:58:33",
        @"userId":@"1801097477426688002",
        @"patientId":@"1806265526245105664",
        @"isMultiple":@(1),
        @"patientName":@"龙马11",
        @"gender":@"Male",
        @"age":@(4),
        @"hemoglobin":@(8.88), //@(420) 888
        @"unit":@"mmol/L",
        @"risk":@"ModerateXXXXX",

    }];
    MJMultipleModel *multipleModel = [[MJMultipleModel alloc]init];
    multipleModel.hemoglobin = recordDataBaseModel;
    
    multipleModel.patientName = recordDataBaseModel.patientName;
    multipleModel.age = recordDataBaseModel.age;
    multipleModel.gender = recordDataBaseModel.gender;
    multipleModel.period = recordDataBaseModel.period;
    multipleModel.createDateTime = recordDataBaseModel.createDateTime;
    multipleModel.detectionId = recordDataBaseModel.detectionId;
    multipleModel.patientId = recordDataBaseModel.patientId;
    multipleModel.userId = recordDataBaseModel.userId;
    multipleModel.isMultiple = recordDataBaseModel.isMultiple;
    return multipleModel;
}

+ (void)jumpMemberInfoViewController:(UIViewController *)viewController patientId:(NSString *)patientId {
    
    BOOL isPreviousViewControllerMemberInfo = false;
    if(viewController.navigationController.viewControllers.count > 1){
        UIViewController *previousViewController = viewController.navigationController.viewControllers[viewController.navigationController.viewControllers.count - 2];

        if([previousViewController isKindOfClass:MemberInfoVC.class]){
            isPreviousViewControllerMemberInfo = true;
            
            NSLog(@"MJLog=======================%@",previousViewController);
        }
    }
    
    if(isPreviousViewControllerMemberInfo){
        [viewController mj_popViewController];
    }else{
        MemberInfoVC *vc = [[MemberInfoVC alloc]initWithPatientId:patientId];
        [viewController.navigationController pushViewController:vc animated:true];
    }
  
}

+ (NSString *)aesEncryptString:(NSString *)string {
    return aesEncryptString(string, kTokenKey)?:@"";
}

+ (void)updateHiLoWithLabel:(UILabel *)label {
    if([label.text isEqualToString:@"Hi"] || [label.text isEqualToString:@"Lo"]){
        label.font = [UIFont fontWithName:@"HarmonyOS_Sans_Condensed_Bold" size:label.font.pointSize];
    }
}

+ (void)interruptionSaveAlertViewWithConfirmBlock:(void(^)(void))confirmBlock cancelBlock:(void(^)(void))cancelBlock {
    
    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
    configure.confirmButtonColor = UIColor.mj_appColor;
    configure.confirmTitle = MJUILocalizedString(@"Yes");
    configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
    configure.messageAlignmentCenter = true;
    configure.disableDismissWindow = true;
    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Interruption Save") message:MJUILocalizedString(@"Save in progress. Are you sure you want to interrupt and abandon?") configure:configure confirmBlock:^{
 
        confirmBlock();
    } cancelBlock:^{

    }];
}

+ (void)loginExpiredAlertViewWithConfirmBlock:(void(^)(void))confirmBlock cancelBlock:(void(^)(void))cancelBlock {
    
    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
    configure.confirmButtonColor = UIColor.mj_appColor;
    configure.confirmTitle = MJUILocalizedString(@"OK_qd");
    configure.messageAlignmentCenter = true;
    configure.disableDismissWindow = true;
    configure.hiddenCancelButton = true;
    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Login expired") message:MJUILocalizedString(@"Logged in on another device. Please re-login to continue use.") configure:configure confirmBlock:^{
 
        confirmBlock();
    } cancelBlock:^{

    }];
}

+ (UIImage *)mj_imageWithLocalizedNamed:(NSString *)name {
    NSArray *nameArray = @[@"en",@"cn",@"tc",@"tc",@"ru",@"id"];
    NSString *nameString = [NSString stringWithFormat:@"%@_%@",name,nameArray[[HealthHelper getLanguageStyle:LanguageHelper.shared.language]]];
    return [UIImage imageNamed:nameString];
}

+ (MJLanguageStyle)getLanguageStyle:(NSString *)language {

    MJLanguageStyle mLanguageStyle = MJLanguageStyleEN;
    if([language isEqualToString:PreferredLanguageEN]){
        mLanguageStyle = MJLanguageStyleEN;
    }
    if([language isEqualToString:PreferredLanguageZhHansCN]){
        mLanguageStyle = MJLanguageStyleZhHansCN;
    }
    if([language isEqualToString:PreferredLanguageZhHantCN]){
        mLanguageStyle = MJLanguageStyleZhHantCN;
    }
    if([language isEqualToString:PreferredLanguageZhHantTW]){
        mLanguageStyle = MJLanguageStyleZhHantTW;
    }
    if([language isEqualToString:PreferredLanguageRU]){
        mLanguageStyle = MJLanguageStyleRU;
    }
    if([language isEqualToString:PreferredLanguageID]){
        mLanguageStyle = MJLanguageStyleID;
    }
    return mLanguageStyle;
}

@end
